<?php


namespace Modules\File\Actions;


use App\Traits\AsAction;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Modules\File\Models\Attachment;

class ImgFetch
{
    use AsAction;


    public function handle(string $url)
    {
        $md5_key = md5($url);
        $disk = Storage::disk('oss');

        $filesystem = new Filesystem();
        $ext = $filesystem->extension($url);

        if(!in_array($ext, ['jpg', 'png', 'gif', 'jpeg'])) {
            return $this->toError(-1, '抓取失败，目前仅支持jpg, png, gif, jpeg格式图片！'.$ext);
        }

        if(!$exist = Attachment::where('uuid', $md5_key)->first()) {
            $path = config('file.path') . date('Y/m/d') . '/';
            $attachName = Str::random(40) . '.' . $ext;
            $result = $disk->put($path . $attachName, Http::get($url)->body());

            if ($result) {
                $data = [
                    'uuid' => $md5_key,
                    'is_remote' => true,
                    'is_sound' => false,
                    'is_approved' => true,
                    'attachment' => $attachName,
                    'file_path' => $path,
                    'file_name' => Arr::last(explode('/', $url)),
                    'file_size' => $disk->size($path . $attachName),
                    'file_type' => ''
                ];
                $exist = Attachment::create($data);
            }
        }

        return [
            'file_id' => $exist->uuid,
            'file_name' => $exist->file_name,
            'file_size' => $exist->file_size,
            'url' => $disk->getUrl($exist['file_path'] . $exist['attachment'])
        ];
    }

}
